<?php
/**
 * The Pagination class
 *
 * @todo pagination pattern support, accept callback function
 */
class Pagination
{
	/**
	 * Constructor placeholder
	 * Prevent the Pagination class from instantiating
	 * Singleton Pattern
	 */
	private function __construct()
	{
	}

	/**
	 * Generate the pagination links
	 * 
	 * @param array $args 
	 * @return string 
	 */
	static public function generate($args)
	{
		/*	if (!isset($args['uri']['query']['start']))
		{
			$args['uri']['query']['start'] = 0;
		}*/
		$args['page_size'] = isset($args['page_size']) ? $args['page_size'] : 10; 
		// $baseUrl = $args['uri']['base'] . $args['uri']['module'] . '/' . $args['uri']['action'];
		$_module = 'index';
		$_action = 'index';
		if (isset($_GET['module']))
		{
			$_module = $_GET['module'];
		}
		if (isset($_GET['action']))
		{
			$_action = $_GET['action'];
		}
		$baseUrl = $args['uri']['base'] . Url::generate($_module, $_action) . '?';
		foreach($_GET as $key => $value)
		{
			if ($key != 'page' && $key != 'module' && $key != 'action')
			{
				$baseUrl .= urlencode($key) . '=' . urlencode($value) . '&';
			}
		}
		$baseUrl .= 'page=';
		$pageTotal = ceil($args['item_total'] / $args['page_size']);
		if (1 >= $pageTotal)
		{
			return '';
		}
		else
		{
			$currentPage = $args['page'];
			$links = '';
			if (1 < $currentPage)
			{
				$previousPage = $currentPage - 1;
				$href = $baseUrl . $previousPage;
				$links .= "\n<a href=\"$href\">上一页</a>";
			}
			$displayPages = 5;
			if ($pageTotal > $displayPages)
			{
				$firstPage = max($currentPage - floor($displayPages / 2), 1);
				$firstPage = min($firstPage, $pageTotal - $displayPages + 1);
				$lastPage = $firstPage + $displayPages - 1;
			}
			else
			{
				$firstPage = 1;
				$lastPage = $pageTotal;
			}

			for ($i = $firstPage; $i <= $lastPage; $i++)
			{
				$href = $baseUrl . $i;
				$links .= $i == $currentPage ? "\n<em>$i</em>" :
				"\n<a href=\"$href\">$i</a>";
			}
			if ($pageTotal > $currentPage)
			{
				$href = $baseUrl . ($currentPage + 1);
				$links .= "\n<a href=\"$href\">下一页</a>";
			}
			return "$links";
		}
	}
}
